import fetch from 'dva/fetch';
import { notification } from 'antd';
import Storage from './localstore';

const errorHandle = (response) => {
  switch (response.status) {
    case 403:
      notification.error('你似乎无权进行该操作');
      return;
    case 404:
      notification.error('你似乎来到了无人区');
      return;
    case 500:
      notification.error('你似乎捅死了服务器');
      return;
    case 502:
      notification.error('你的网速似乎可以溺死一条龙虾');
      return;
    default:
      notification.error('你干了啥？');
  }
};

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response.json().then((result) => {
      if (result.code === 'OK') {
        return result.data;
      }
      // 异常抛出
      notification.error({
        message: result.msg,
      });
      const error = new Error(result.msg);
      // error.response = response
      throw error;
    });
  } else {
    errorHandle(response);
    return response.json().then((result) => {
      if (result.code) {
        notification.error({
          message: result.name,
          description: result.message,
        });
      }
      if (result.stack) {
        notification.error({
          message: '请求错误',
          description: result.message,
        });
      }
      const error = new Error(result.message);
      error.response = response;
      throw error;
    });
  }
}

/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */
export default function request(url, options) {
  const token = Storage.get('access_token') || '';
  const defaultOptions = {
    // credentials: 'include',
    // mode: 'no-cors',
    headers: {
      Authorization: `Bearer ${token}`,
    },
  };

  const newOptions = { ...defaultOptions,
    ...options,
  };

  if (newOptions.method === 'POST' || newOptions.method === 'PUT') {
    newOptions.headers = {
      Accept: 'application/json',
      'Content-Type': 'application/json; charset=utf-8',
      ...newOptions.headers,
    };
    newOptions.body = JSON.stringify(newOptions.body);
  }

  return fetch(url, newOptions)
    .then(checkStatus)
    .then(resp => resp)
    .catch(err => ({
      err,
    }));
}
